const fs = require('fs');
//自动生成路由
let routesFiles;
try {
    routesFiles = fs.readdirSync('./routes');
} catch (err) {
    console.log('不存在路由文件夹:routes');
    process.exit(0);
}

let index = ''

//引入路由组件
index += "const router = require('express').Router();\n";

routesFiles.forEach(file => {
    if (/\.js/.test(file) && !/^index\.js$/.test(file)) {
        let routers = require(`./routes/${file}`);
        Object.keys(routers).forEach(router => {
            if (router != 'publicMiddleware') {
                routers[router].myMiddleware = ['validate'].concat(routers[router].myMiddleware).concat(routers.publicMiddleware);
                if (routers[router].myMiddleware.length) {
                    routers[router].myMiddleware.forEach(_myMiddleware => {
                        const reg = new RegExp(`const ${_myMiddleware} = require\\(\\'\\.\\./middleware/${_myMiddleware}\\'\\);`);
                        if (!reg.test(index)) {
                            //引入中间件
                            index += `const ${_myMiddleware} = require('../middleware/${_myMiddleware}');\n`;
                        }
                    });
                }
            }
        })
    }
})
index += `\n`
let document = `# ${require('./package.json').name}API文档 #\n\n\n`;
routesFiles.forEach(file => {
    if (/\.js/.test(file) && !/^index\.js$/.test(file)) {
        let routers = require(`./routes/${file}`);
        file = file.slice(0, -3);
        //引入业务函数
        index += `const ${file} = require('./${file}');\n`;
        document += `<ul>\n\n`;
        Object.keys(routers).forEach(router => {
            if (router != 'publicMiddleware') {
                if (routers[router].myMiddleware.length) {
                    const myMiddleware = routers[router].myMiddleware.join(', ');
                    index += `router.${routers[router].method}('/${file}/${router}', ${myMiddleware}, ${file}.${router}.run);\n`;
                } else {
                    index += `router.${routers[router].method}('/${file}/${router}', ${file}.${router}.run);\n`;
                }
                document += `<li> 描述: ${routers[router].describe}\n`;
                document += `<ul>\n<li>路由: <code>/${file}/${router}</code></li>\n`;
                document += `<li>方式: <code>${routers[router].method}</code></li>\n`;
                document += `<li>参数:`;
                document += `<table>\n`;
                document += `<tr>\n`;
                document += `<td>args</td><td>type</td><td>require</td>\n`;
                document += `</tr>\n`;
                let my_args = routers[router].args;
                for (const key in my_args) {
                    if (my_args.hasOwnProperty(key)) {
                        const element = my_args[key];
                        document += `<tr>\n`;
                        document += `<td>${key}</td><td>${element.type.name}</td><td>${!!element.require}</td>\n`;
                        document += `</tr>\n`;
                    }
                }

                document += `</table>\n</li>\n</ul>\n`;
                document += `</li>\n\n`;
            }
        })
        document += `</ul>\n\n`;
        index += `\n`;
    }
});

index += `module.exports = router; \n`

fs.writeFile('./routes/index.js', index, err => {
    if (err) {
        console.log('生成路由文件失败\n' + err);
        process.exit(0);
    } else {
        console.log('生成路由文件/router/index.js成功!');
    }
})

//生成参数验证的中间件
const validate = `module.exports = function (req, res, next) {
    const path = req.path.substring(1).split('/');
    const args = require('../routes/' + path[0])[path[1]].args;
    const method = req.method;
    let parameters;
    if (method == 'GET') {
        parameters = req.query;
    } else if (method == 'POST') {
        parameters = req.body;
    }
    if (Object.keys(args).some(arg =>
        !parameters[arg] != !args[arg].require || Object.prototype.toString.call(parameters[arg]) !== \`[object \${args[arg].type.name}]\`
    )) {
        return res.json({
            code: 2101,
            message: '参数不全或类型错误'
        })
    } else {
        next()
    }
}`

fs.writeFile('./middleware/validate.js', validate, err => {
    if (err) {
        console.log('生成参数验证中间件文件失败\n' + err);
        process.exit(0);
    } else {
        console.log('生成参数验证中间件文件/middleware/validate.js成功!');
    }
})

//生成api文档
fs.writeFile('./README.md', document, err => {
    if (err) {
        console.log('生成API文档失败\n' + err);
    } else {
        console.log('生成API文档/README.md成功!');
    }
})